package com.jie.client.service.ui.view;

import com.jie.client.core.ClientApplication;
import com.jie.client.core.handler.ClientWriteHandler;
import com.jie.client.service.entity.model.User;
import com.jie.client.service.ui.constant.ViewMapConstant;
import com.jie.client.service.ui.model.SetNode;
import com.jie.client.service.ui.model.UserItemNode;
import com.jie.client.service.ui.view.cell.UserListCell;
import com.jie.client.service.ui.view.item.FollowItem;
import com.jie.client.service.ui.view.item.UserItem;
import javafx.collections.ObservableList;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.input.MouseButton;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.scene.text.Text;
import javafx.stage.Stage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * 关注视图
 * @author XieZhiJie
 * @date 2022/04/29 14:27
 */
public class FollowView {

    private final Logger logger = LoggerFactory.getLogger(FollowView.class);

    /**
     * 存放关注用户的列表
     */
    public final TableView<FollowItem> followItemTableView = new TableView<>();

    public void createFollowView() {
        // 将当前视图放入
        ClientApplication.VIEW_MAP.put(ViewMapConstant.FOLLOW_VIEW, this);
        Stage primaryStage = new Stage();
        // 初始化所有控件
        // 放所有布局的VBox
        VBox friendViewBox = new VBox();
        // 放置所有按钮的Box
        HBox buttonBox = new HBox();
        Text tipText = new Text("选中某一行点击以下按钮进行操作");
        Button addFriendButton = new Button("添加关注");
        Button seeRemarkButton = new Button("查看备注");
        Button changeRemarkButton = new Button("修改备注");
        Button deleteFriendButton = new Button("删除关注");

        // 设置friendViewBox的控件间距
        friendViewBox.setPadding(new Insets(10, 10, 20, 10));
        friendViewBox.setSpacing(20);

        // 放置控件位置
        buttonBox.getChildren().add(addFriendButton);
        buttonBox.getChildren().add(seeRemarkButton);
        buttonBox.getChildren().add(changeRemarkButton);
        buttonBox.getChildren().add(deleteFriendButton);
        friendViewBox.getChildren().add(this.followItemTableView);
        friendViewBox.getChildren().add(tipText);
        friendViewBox.getChildren().add(buttonBox);

        // 设置Table里的列名字
        TableColumn<FollowItem, String> userIdentColumn = new TableColumn<>("用户标识");
        TableColumn<FollowItem, String> remarkColumn = new TableColumn<>("备注");

        // 为列创建数据属性
        userIdentColumn.setCellValueFactory(
                new PropertyValueFactory<>("userIdent")
        );
        remarkColumn.setCellValueFactory(
                new PropertyValueFactory<>("remark")
        );
        userIdentColumn.setPrefWidth(278);
        remarkColumn.setPrefWidth(128);
        // 添加列名
        this.followItemTableView.getColumns().add(userIdentColumn);
        this.followItemTableView.getColumns().add(remarkColumn);

        // 设置按钮间的距离
        buttonBox.setSpacing(30);

        // 设置查看为添加关注的按钮
        addFriendButton.setOnAction(event -> onNotFollowUserListAction());
        // 设置查看备注的按钮
        seeRemarkButton.setOnAction(event -> onSeeRemarkAction());
        // 设置修改备注的按钮
        changeRemarkButton.setOnAction(event -> onChangeRemarkAction());
        // 设置删除关注的按钮
        deleteFriendButton.setOnAction(event -> onDeleteAction());
        // 设置鼠标双击的私聊
        this.followItemTableView.setOnMouseClicked(this::onSingleChatAction);

        // 布置场景
        Scene scene = new Scene(friendViewBox, 430, 500);
        primaryStage.setTitle("关注列表(双击私聊)");
        primaryStage.setScene(scene);
        primaryStage.show();

        primaryStage.setOnCloseRequest(event -> ClientApplication.VIEW_MAP.remove(ViewMapConstant.FOLLOW_VIEW));
    }

    /**
     * 打开未关注用户列表
     */
    private void onNotFollowUserListAction() {
        if (ClientApplication.VIEW_MAP.containsKey(ViewMapConstant.NOT_FOLLOW_USER_LIST)) {
            return;
        }
        // 初始化所有控件
        Stage stage = new Stage();
        VBox notFBox = new VBox();
        ListView<UserItem> notFUsersList = new ListView<>();
        Button okButton = new Button("确认添加");
        notFBox.getChildren().add(notFUsersList);
        notFBox.getChildren().add(okButton);
        notFBox.setPadding(new Insets(10, 5, 10, 5));
        notFBox.setSpacing(10);
        VBox.setMargin(okButton, new Insets(0, 0, 0, 210));

        ClientApplication.VIEW_MAP.put(ViewMapConstant.NOT_FOLLOW_USER_LIST, new UserItemNode(notFUsersList));
        // 退出这个窗口的时候删掉这个view
        stage.setOnCloseRequest(event -> ClientApplication.VIEW_MAP.remove(ViewMapConstant.NOT_FOLLOW_USER_LIST));
        // 添加确认事件到按钮上
        okButton.setOnAction(event -> onAddFollowAction(notFUsersList));
        // 设置列表怎么展示
        notFUsersList.setCellFactory(param -> new UserListCell());
        // 布置场景
        Scene scene = new Scene(notFBox, 300, 450);
        stage.setTitle("非关注用户");
        stage.setScene(scene);
        stage.show();
        Map<String, Object> map = new HashMap<>(2);
        map.put("choice", "getNotFollowUserList");
        ClientWriteHandler.sendRequest(map);
    }

    /**
     * 添加关注动作
     */
    private void onAddFollowAction(ListView<UserItem> userItemListView) {
        UserItem userItem;
        try {
            userItem = userItemListView.getSelectionModel().getSelectedItems().get(0);
        } catch (ArrayIndexOutOfBoundsException e) {
            return;
        }
        if (userItem != null) {
            Map<String, Object> map = new HashMap<>(4);
            map.put("choice", "addFollow");
            map.put("otherUserId", userItem.getUserId());
            map.put("remark", userItem.getUserIdent());
            ClientWriteHandler.sendRequest(map);
        }
    }

    /**
     * 查看备注
     */
    private void onSeeRemarkAction() {
        FollowItem followItem = this.followItemTableView.getSelectionModel().getSelectedItem();
        if (followItem == null) {
            return;
        }
        // 生成一个窗口展示这条信息
        Stage stage = new Stage();
        TextArea aRemarksText = new TextArea();

        // 不可编辑
        aRemarksText.setEditable(false);

        aRemarksText.appendText(followItem.getRemark());

        // 布置场景
        Scene scene = new Scene(aRemarksText, 300, 100);
        stage.setTitle("备注");
        stage.setScene(scene);
        stage.show();
    }

    /**
     * 修改备注动作
     */
    private void onChangeRemarkAction() {
        FollowItem followItem = this.followItemTableView.getSelectionModel().getSelectedItem();
        if (followItem == null) {
            return;
        }
        // 生成一个窗口展示这条信息
        Stage stage = new Stage();

        // 生成布局
        VBox changeRemarksBox = new VBox();
        // 可修改
        TextArea remarkText = new TextArea();
        Button okButton = new Button("确认");
        changeRemarksBox.getChildren().add(remarkText);
        changeRemarksBox.getChildren().add(okButton);
        changeRemarksBox.setPadding(new Insets(10, 5, 10, 5));
        changeRemarksBox.setSpacing(10);
        VBox.setMargin(okButton, new Insets(0, 0, 0, 240));

        // 设置事件(点击确认就修改)
        okButton.setOnAction(event -> {
            Map<String, Object> map = new HashMap<>(4);
            map.put("choice", "updateFollow");
            Integer otherUserId = Integer.parseInt(followItem.getUserId());
            map.put("otherUserId", otherUserId);
            map.put("remark", remarkText.getText().trim());
            ClientWriteHandler.sendRequest(map);
            stage.close();
        });

        // 添加原先的备注信息
        remarkText.appendText(followItem.getRemark());

        // 布置场景
        Scene scene = new Scene(changeRemarksBox, 300, 100);
        stage.setTitle("修改备注");
        stage.setScene(scene);
        stage.show();
    }

    /**
     * 点击删除操作
     */
    private void onDeleteAction() {
        FollowItem followItem = this.followItemTableView.getSelectionModel().getSelectedItem();
        if (followItem == null) {
            return;
        }
        Map<String, Object> map = new HashMap<>(2);
        map.put("choice", "cancelFollow");
        map.put("userId", followItem.getUserId());
        ClientWriteHandler.sendRequest(map);
    }

    /**
     * 点击事件
     * @param event 事件
     */
    private void onSingleChatAction(MouseEvent event) {
        if (event.getButton() == MouseButton.PRIMARY && event.getClickCount() == 2) {
            ObservableList<FollowItem> followData = this.followItemTableView.getItems();
            int index = this.followItemTableView.getSelectionModel().getSelectedIndex();
            if (index < 0 || index >= followData.size()) {
                logger.info("点到空白内容了...");
            }
            FollowItem followItem = followData.get(index);
            SetNode singleChatSetNode = (SetNode) ClientApplication.VIEW_MAP.get(ViewMapConstant.SINGLE_CHAT_SET);
            Set<Integer> singleChatSet = singleChatSetNode.set;
            if (singleChatSet.contains(Integer.parseInt(followItem.getUserId()))) {
                logger.info("私聊已存在...");
                return;
            }
            singleChatSet.add(Integer.parseInt(followItem.getUserId()));
            User choiceUser = new User();
            choiceUser.setUserId(followItem.getUserId());
            choiceUser.setUserAccount(followItem.getUserAccount());
            choiceUser.setUsername(followItem.getUsername());
            new SingleChatView(ClientApplication.USER, choiceUser, singleChatSet).createSingleChatView();
        }
    }

}
